document.addEventListener("deviceready", onDeviceReady, false);

function onDeviceReady() {
	// just for debug info
	RssHelper.toast("欢迎使用RSS阅读器!");
	// refresh the feed content
	refresh_feed_content();
	
}

// phone information
function show_phone_information() {
	alert("名称: \t" + window.device.name + '<br/>'
							+ "平台: \t" + window.device.platform + '<br/>'
							+ "UUID: \t" + window.device.uuid + '<br/>'
							+ "版本: \t" + window.device.version + '<br/>');
}

document.addEventListener("backbutton", onBackKeyDown, false);

var back_click_count = 0;
function onBackKeyDown() {
   // 返回
	navigator.app.backHistory();
}

/**
 * show the detail content of the specified news' url
 */
function open_url(link) {
	// 在SimpleBrowser中打开网页, 使用新浪微博对html进行转换为手机容易阅读的wml
	RssHelper.openUrlInBrowser("http://h2w.iask.cn/hd.php?u=" + link);
	
}

/**
 * refresh button's function
 */
function refresh_feed_content() {
	RssHelper.toast("正在更新RSS内容");
	navigator.notification.vibrate(200);
	$("#rss_channel_content").empty().html("正在加载中...");
	$("#carousel_feed_content").empty().html("正在加载中...");
    var urlList ;
	
	var db = window.openDatabase("RssDB", "1.0", "Rss DB", 1000000);
	function querySuccess(tx, results) {
		if(results.rows.length>0){
			var urlList = [];
			for (var i=0; i<results.rows.length; i++){
				var listItem = {};
				listItem.url = results.rows.item(i).url;
				listItem.uid = results.rows.item(i).uid;
				urlList.push(listItem);
			}
			get_rss_feed(urlList);
		}else {
			RssHelper.toast("第一次使用, 加载默认rss.");
			tx.executeSql('INSERT INTO RSS_GROUP (gid, name) VALUES (\'1\',\'default\');');
			var urlList = [{url:"http://news.163.com/special/00011K6L/rss_newstop.xml",name:"网易",gid:1,uid:1}, 
			               {url:"http://news.sohu.com/rss/pfocus.xml",name:"搜狐",gid:1,uid:2}, 
			               {url:"http://cnbeta.feedsportal.com/c/34306/f/624776/index.rss",name:"cnbeta",gid:1,uid:3}, 
			               {url:"http://news.baidu.com/n?cmd=1&class=civilnews&tn=rss",name:"百度",gid:1,uid:4}, 
			               {url:"http://news.baidu.com/n?cmd=1&class=gamenews&tn=rss",name:"百度游戏",gid:1,uid:5}];
			db.transaction(function(tx){
				for(var i in urlList) {
					tx.executeSql('INSERT INTO RSS_URL (uid, gid, name, url) VALUES (\'' + urlList[i].uid + '\',\'' + urlList[i].gid +'\',\'' + urlList[i].name + '\',\'' + urlList[i].url +'\');');
				}},errorCB,successCB);
			get_rss_feed(urlList);
		}
		if (!results.rowsAffected) {
		  return false;
		}
	}
		
		function populateDB(tx) {
			 tx.executeSql('DROP TABLE IF EXISTS RSS_CONTENT;'); // 删除RSS_CONTENT表和其中的内容, 每次重新装载, 保证是最新的数据
		     tx.executeSql('CREATE TABLE IF NOT EXISTS RSS_URL (uid, gid, name unique, url unique);');
		     tx.executeSql('CREATE TABLE IF NOT EXISTS RSS_GROUP (gid, name unique);');
		     tx.executeSql('SELECT * FROM RSS_URL',[],querySuccess,errorCB);
		}

		db.transaction(populateDB, errorCB, successCB);
		
		function errorCB(err) {
		}
		function successCB() {
		}
}

/**
 * get all rss feed
 */
function get_rss_feed(urls) {
	var home_count = 0;
	
	// 在content中添加显示每个新闻的panel, id设置为url
	var panel_parent = document.getElementById('content');
	
	// 显示所用的RSS频道
	var rss_parent = document.getElementById('rss_channel_content');
	$("#rss_channel_content").empty();
	$("#carousel_feed_content").empty();
	var rss_child = document.createElement('div');
	rss_parent.appendChild(rss_child);
	
	for (var i = 0; i < urls.length; ++i) {
		var url = urls[i].url; // rss的url
//		var uid = urls[i].uid; // rss的uid
		var now = new Date().getTime();
		var count = 0; // 更新计数器, 完成了几次更新

		// custom phonegap plugin
		RssHelper.getUrlContent(url, i,
		// 数据接收完后的处理
		function(result) {
			var ul_id = 'feed_content_' + result.index;
			
			data = $.parseXML(result.data);
			// 频道名称
			var li_channel_title = document.createElement('h1');
			li_channel_title.setAttribute('onclick', 'showHide(this,\"' + ul_id + '\");');
			li_channel_title.setAttribute('class', 'collapsed');
			var channel = $(data).find('channel');
			var channel_title = channel.find('title').text();
			var channel_link = channel.find('link').text();
			var channel_description = channel.find('description').text();
	        var html = channel_title;
			li_channel_title.innerHTML = html;
			var li_channel_description = document.createElement('p');
			li_channel_description.innerHTML = channel_description;
			rss_child.appendChild(li_channel_title);
			rss_child.appendChild(li_channel_description);
			
			var channel_content_list = document.createElement('ul');
			$(channel_content_list).hide();
			channel_content_list.setAttribute('id', ul_id);
			channel_content_list.setAttribute('title', channel_title);
			rss_child.appendChild(channel_content_list);
			
			$(data).find('channel').find('item').each(
					function() {
						//name the current found item this for this particular loop run
						var $item = $(this);
						// grab the post title
						var title = $item.children('title').text(); // .replace("<![CDATA[", "").replace("]]>", "")
						// grab the post's URL
						var link = $item.children('link').text();
						// next, the description
						var description = $item.children('description').text();
						//don't forget the pubdate
						var pubDate = $item.children('pubDate').text();
						var li_item = document.createElement('li');
						// now create a var 'html' to store the markup we're using to output the feed to the browser window
						var html = "<a onclick=\"open_url('" + link+ "');\">" + title + "<\/a>";
						li_item.innerHTML = html;
						//put that feed content on the screen!
						channel_content_list.appendChild(li_item);
						var rss_content_id = 0;
						saveRssContentToDatabase(rss_content_id++, title, link, description, pubDate, 1);
						if (home_count < 20 && Math.round(Math.random() * 10) == 6) {
							var carousel_content_div = document.createElement('p');
						    carousel_content_div.innerHTML = "<a onclick=\"open_url('" + link + "');\"><p align=\"center\">" + title + "<\/p>"
						    								+ "<pre id=\"description\" onclick=\"return false;\" class=\"feed_description\">" 
						    								// description 取出a和img tag .replace(/<\/?(a|img).*\/?>/gi,'')
						    								+ description.replace(/[ ]+/, ' ').replace(/&(lt|gt);/g, function (strMatch, p1){
						    									return (p1 == "lt")? "<" : ">";}).replace(/<\/?[a][^>]*>/g, "") + "<\/pre>"
						    								+ "<p>publish at: "+ pubDate + "<\/p><\/a>";
						    document.getElementById('carousel_feed_content').appendChild(carousel_content_div);
						    
						    $("#description").find("img").each(function() {
						    	$(this).attr('onclick', '');
						    });
						    $("#description").find("a").each(function() {
						    	$(this).remove();
						    });
						    ++home_count;
						}
					});
			
			// 显示加载时间 debug
			//alert(new Date().getTime() - now); 
			if (count == urls.length - 1) {
				navigator.notification.vibrate(200);
				RssHelper.toast("加载完成!");
			} else {
				++count;
				RssHelper.toast("已完成" + count + "/" + urls.length + ".");
			}
		}, 
		// 错误处理
		function(message) {
			navigator.notification.vibrate(400);
			RssHelper.toast("无法读取RSS内容: " + url + ", message -> " + message);
		});
	}
}

var saveRssContentToDatabase = function(id, title, link, description, pubDate, uid) {
	 var db = window.openDatabase("RssDB", "1.0", "Rss DB", 1000000);
	db.transaction(populateDB, errorCB, successCB);

	function populateDB(tx) {
	     tx.executeSql('CREATE TABLE IF NOT EXISTS RSS_CONTENT (id text, title text, link text, description text, pubDate text, uid text)');
	     db.transaction(function(tx){
				tx.executeSql('INSERT INTO RSS_CONTENT (id, title, link, description, pubDate, uid) VALUES ("' + id + '", '  
						+ title + '", ' + link + '", ' + description + '", ' + pubDate + '", ' + uid + '")');
	     	}, successCB, errorCB);
	}

	function errorCB(err) {
	}
	function successCB() {
	}
}
